﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.JScript;

namespace aliwinform
{
    public struct acctk
    {
        public string uid;
        public string aliId;
        public string resource_owner;
        public string memberId;
        public string expires_in;
        public string refresh_token;
        public string access_token;
    }
    public partial class Form1 : Form
    {
        public static acctk acctk2 ;
        string appKey = Properties.Settings.Default.appKey;
        string site = Properties.Settings.Default.site;
        string secretkey = Properties.Settings.Default.secretkey;
        string redirect_uri = Properties.Settings.Default.redirect_uri;
        string account = Properties.Settings.Default.account;
        string password = Properties.Settings.Default.password;
        //public acctk acctk1;

        public Dictionary<string, string> prm = new Dictionary<string, string>();

        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
       string   code1 = getcode();
    acctk2=   getaccesstoken(code1);
        }

        private string getcode()
        {
            richTextBox1.Text += "你的appkey是" + appKey;
            this.prm.Add("client_id", this.appKey);
            this.prm.Add("site", this.site);
            this.prm.Add("redirect_uri", this.redirect_uri);
            string aop_signature = sign(prm, this.secretkey);
            richTextBox1.Text += "你的signature是" + aop_signature;

            string oauth = string.Format("http://gw.open.1688.com/auth/authorize.htm?client_id={0}&site=china&redirect_uri={1}&_aop_signature={2}", this.appKey, this.redirect_uri, aop_signature);
            //  System.Diagnostics.Process.Start(oauth);
            CookieContainer MyCookieContainer = new CookieContainer();
            HttpWebRequest http = WebRequest.Create(oauth) as HttpWebRequest;
            http.Referer = oauth;
            http.Method = "POST";
            http.ContentType = "application/x-www-form-urlencoded";
            http.AllowAutoRedirect = true;
            http.KeepAlive = true;
            http.CookieContainer = MyCookieContainer;
            HttpWebResponse response = http.GetResponse() as HttpWebResponse;


            StreamReader reader = new StreamReader(response.GetResponseStream());

            string org = reader.ReadToEnd().ToString();
            //richTextBox1.Text += reader.ReadToEnd().ToString();
            string r = "<input type=\"hidden\" name=\"recordId\" value=\"(\\w+)(.\\w+)(.\\w+)(.\\w+)(.\\w+)";
            var match = Regex.Match(org, r);
            string rich = match.Groups[1].Value;
            rich += match.Groups[2].Value;
            rich += match.Groups[3].Value;
            rich += match.Groups[4].Value;
            rich += match.Groups[5].Value;
            richTextBox1.Text += "你的recordId是" + rich;
            string r2 = "<input name='_csrf_token' type='hidden' value='(\\w+)";
            var match2 = Regex.Match(org, r2);
            string rich2 = match2.Groups[1].Value;
            richTextBox1.Text += "你的_csrf_token是" + rich2;

            HttpWebRequest http2 = WebRequest.Create(oauth) as HttpWebRequest;
            http2.Referer = oauth;
            http2.Method = "POST";
            http2.ContentType = "application/x-www-form-urlencoded";
            http2.AllowAutoRedirect = true;
            http2.KeepAlive = true;
            http2.CookieContainer = MyCookieContainer;
            string postBody = string.Format("action=AuthorizeAction&event_submit_do_accept_auth=submit&siteId=CN&authpage=client%2FchinaAuthrization&recordId={0}&_csrf_token={1}&account={2}&password={3}", rich, rich2, account, password);
            byte[] postData = Encoding.Default.GetBytes(postBody);
            http2.ContentLength = postData.Length;

            using (Stream request2 = http2.GetRequestStream())
            {
                try
                {
                    request2.Write(postData, 0, postData.Length);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    request2.Close();
                }
            }
            string code = string.Empty;

            HttpWebResponse response1 = http2.GetResponse() as HttpWebResponse;


            StreamReader reader1 = new StreamReader(response1.GetResponseStream());

            string codeuri = response1.ResponseUri.ToString();
            string codeout = codeuri.Substring(codeuri.IndexOf("code") + 5);
            richTextBox1.Text += "你获取的code是:" + codeout;

            // return;


            // string lingpaigeturl = string.Format("https://gw.open.1688.com/openapi/http/1/system.oauth2/getToken/{0}?grant_type=authorization_code&need_refresh_token=true&client_id={1}&client_secret={2}&redirect_uri={3}&code={4}", appKey, appKey, secretkey, redirect_uri, codeout);
            // string lingpaigeturl2 = string.Format("http://gw.open.1688.com/openapi/http/1/system.oauth2/getToken/{0}?", appKey);
           // getaccesstoken(codeout);
            //  wc.UploadDataAsync(new Uri(baseUrl), "POST", bytes);
            //   wc.UploadDataCompleted += wc_UploadDataCompleted;
            //  richTextBox1.Text += "你获取的令牌返回是:" + lingpaigeturl;       
            //  //  System.Diagnostics.Process.Start(lingpaigeturl);
            //NewMethod(MyCookieContainer);


            webBrowser1.Url = new Uri(oauth);
            return codeout;
        }

        private void gethttpwithuri(string lingpaigeturl2)
        {
            HttpWebRequest http23 = WebRequest.Create(lingpaigeturl2) as HttpWebRequest;
            // http23.ServicePoint.Expect100Continue = false;
            //http23.Referer = lingpaigeturl;
            http23.Method = "GET";
            http23.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            // http23.AllowAutoRedirect = true;
            //  http23.Credentials = System.Net.CredentialCache.DefaultCredentials;
            http23.KeepAlive = true;
            http23.AllowAutoRedirect = true;
          //  http23.ProtocolVersion = HttpVersion.Version10;
          //  http23.CookieContainer = MyCookieContainer;
            //using (Stream request2 = http23.GetRequestStream())
            //{
            //    try
            //    {
            //        // request2.Write(postData, 0, postData.Length);
            //    }
            //    catch
            //    {
            //        throw;
            //    }
            //    finally
            //    {
            //        request2.Close();
            //    }
            //}
            try
            {
                HttpWebResponse response12 = http23.GetResponse() as HttpWebResponse;
                StreamReader reader12 = new StreamReader(response12.GetResponseStream());
                richTextBox3.Text += "你获取的uri返回是:" + reader12.ReadToEnd().ToString();
            }
            catch (System.Exception ex)
            {
                throw (ex);
            }
        }

        private acctk getaccesstoken(string codeout)
        {
            WebClient wc = new WebClient();
            string baseUrl = string.Format("https://gw.open.1688.com/openapi/http/1/system.oauth2/getToken/{0}", appKey);
            string upstr1 = string.Format("client_id=1009066&redirect_uri=http%3A%2F%2Fgw.open.1688.com%2Fauth%2FauthCode.htm&code={0}&client_secret=aiN%2B~i~ab4_p&grant_type=authorization_code&need_refresh_token=true", codeout);
            string upstr = string.Format("client_id={0}&redirect_uri={1}&code={2}&client_secret={3}&grant_type=authorization_code&need_refresh_token=true", appKey, Microsoft.JScript.GlobalObject.encodeURIComponent(redirect_uri), codeout, Microsoft.JScript.GlobalObject.encodeURIComponent(secretkey));
            string upout = Microsoft.JScript.GlobalObject.encodeURIComponent(upstr);
            byte[] bytes = Encoding.UTF8.GetBytes(upstr);
            // wc.BaseAddress = baseUrl;
            wc.Encoding = System.Text.Encoding.UTF8;
            wc.Headers.Add(HttpRequestHeader.Accept, "json");
            wc.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded; charset=UTF-8");
            wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
            //wc.Headers.Add("Accept", "application/json, text/javascript, */*; q=0.01");
            //wc.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            //wc.Headers.Add("Accept-Language", "zh-CN");
            //wc.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)");
            //wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            // wc.Headers.Add("ContentLength",bytes.Length.ToString()); 
            // wc.UploadStringCompleted += wc_UploadStringCompleted;
            //  wc.UploadStringAsync(new Uri(baseUrl), "POST",upstr1);
            string tkout = wc.UploadString(baseUrl, "POST", upstr);
            richTextBox1.Text += "你获取的令牌返回是:" + tkout;
            string pattern1 = "{\"uid\":\"(?<uid>\\d+)\",\"aliId\":\"(?<aliId>\\d+)\",\"resource_owner\":\"(?<resource_owner>\\w+)\",\"memberId\":\"(?<memberId>\\S+)\",\"expires_in\":\"(?<expires_in>\\d+)\",\"refresh_token\":\"(\\w+)(.\\w+)(.\\w+)(.\\w+)(.\\w+)\",\"access_token\":\"(\\w+)(.\\w+)(.\\w+)(.\\w+)(.\\w+)\"}";
            Match match = Regex.Match(tkout, pattern1);
            richTextBox1.Text += match.Groups.Count;
            string refresh_token1 = string.Empty;
            for (int i = 1; i < 6; i++)
            {
                refresh_token1 += match.Groups[i].Value;
            }

            string access_token1 = string.Empty;
            for (int i = 6; i < 11; i++)
            {
                access_token1 += match.Groups[i].Value;
            }
            acctk acctk1 = new acctk()
               {
                   access_token=access_token1,
                   refresh_token=refresh_token1,
                   uid = match.Groups["uid"].Value,
                   aliId = match.Groups["aliId"].Value,
                   resource_owner = match.Groups["resource_owner"].Value,
                   memberId = match.Groups["memberId"].Value,
                   expires_in = match.Groups["expires_in"].Value,
               };
            //   richTextBox1.Text += "是" +refresh_token + "是" + access_token + "是" + uid + "是" + aliId + "是" + resource_owner + "是" + memberId + "是" + expires_in;
            return acctk1;
        }

        //void wc_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        //{
        //    richTextBox1.Text += "你获取的令牌返回是:" + e.Result.ToString();
        //}

        //void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        //{
        //    richTextBox1.Text += "你获取的令牌返回是:" + e.Result.ToString();
        //}


        private string sign(Dictionary<string, string> paramDic, string appSecret)
        {
            byte[] signatureKey = Encoding.UTF8.GetBytes(appSecret);
            //第一步：拼装key+value
            List<string> list = new List<string>();
            foreach (KeyValuePair<string, string> kv in paramDic)
            {
                list.Add(kv.Key + kv.Value);
            }
            //第二步：排序
            list.Sort();
            //第三步：拼装排序后的各个字符串
            string tmp = "";
            foreach (string kvstr in list)
            {
                tmp = tmp + kvstr;
            }
            //第四步：将拼装后的字符串和app密钥一起计算签名
            //HMAC-SHA1
            HMACSHA1 hmacsha1 = new HMACSHA1(signatureKey);
            hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(tmp));
            byte[] hash = hmacsha1.Hash;
            //TO HEX
            return BitConverter.ToString(hash).Replace("-", string.Empty).ToUpper();
        }
        private string sign(string urlPath, Dictionary<string, string> paramDic)
        {
            byte[] signatureKey = Encoding.UTF8.GetBytes(secretkey);//此处用自己的签名密钥
            List<string> list = new List<string>();
            foreach (KeyValuePair<string, string> kv in paramDic)
            {
                list.Add(kv.Key + kv.Value);
            }
            list.Sort();
            string tmp = urlPath;
            foreach (string kvstr in list)
            {
                tmp = tmp + kvstr;
            }

            //HMAC-SHA1
            HMACSHA1 hmacsha1 = new HMACSHA1(signatureKey);
            hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(tmp));
            /*
            hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(urlPath));
            foreach (string kvstr in list)
            {
                hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(kvstr));
            }
             */
            byte[] hash = hmacsha1.Hash;
            //TO HEX
            return BitConverter.ToString(hash).Replace("-", string.Empty).ToUpper();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string access_token2="";
            string dcs = "";
            string signolduri = richTextBox2.Text.Substring(richTextBox2.Text.IndexOf("openapi") + 8, richTextBox2.Text.IndexOf("?") - richTextBox2.Text.IndexOf("openapi") - 8);
            if (checkBox1.Checked == false)
            {
                dcs = HttpUtility.UrlDecode(richTextBox2.Text.Substring(richTextBox2.Text.IndexOf("?") + 1));

            }
            else
            {
                if (acctk2.access_token != null)
                {
                    access_token2 = acctk2.access_token;
                    dcs = HttpUtility.UrlDecode(richTextBox2.Text.Substring(richTextBox2.Text.IndexOf("?") + 1)) + "&access_token=" + access_token2;
                }
                else
                {
                    string code1 = getcode();
                    acctk2 = getaccesstoken(code1);
                    access_token2 = acctk2.access_token;
                    dcs = HttpUtility.UrlDecode(richTextBox2.Text.Substring(richTextBox2.Text.IndexOf("?") + 1)) + "&access_token=" + access_token2;
                }
            }// string signolduri = richTextBox2.Text.Substring(0, richTextBox2.Text.IndexOf("?"));
            //MessageBox.Show(webBrowser1.Url.ToString());
          
            string dcsm = @"([^&]+?)=([^&]+)";
            MatchCollection matchs = Regex.Matches(dcs, dcsm);
            
            Dictionary<string, string> dicwithuri = new Dictionary<string, string>();
            foreach(Match m in matchs)
            {
        dicwithuri.Add(m.Value.Substring(0,m.Value.IndexOf("=")),m.Value.Substring(m.Value.IndexOf("=")+1));
            }
           // MessageBox.Show(dicwithuri.Count.ToString());
         
            string signwithuri = sign(signolduri, dicwithuri);
            richTextBox3.Text +="你获取到的uri签名是" +signwithuri;
            string signwithuriout = "";
            if (checkBox1.Checked == true)
            {
                 signwithuriout = richTextBox2.Text + "&access_token=" + access_token2 + "&_aop_signature=" + signwithuri;
            }
            else
            {
                 signwithuriout = richTextBox2.Text + "&_aop_signature=" + signwithuri;
            }
            richTextBox3.Text += "你获取到的带签名的uri是" + signwithuriout;
            
            gethttpwithuri(signwithuriout);
          //  System.Diagnostics.Process.Start(signwithuriout);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}
